<template>
  <view class="cart-container">
    <!-- 顶部背景 -->
    <view class="cart-header-bg"></view>
    
    <!-- 店铺信息 -->
    <view class="shop-info">
      <view class="shop-info-inner">
        <u-avatar :src="shopInfo.logo || '/static/logo.png'" size="50" class="shop-logo"></u-avatar>
        <view class="shop-info-text">
          <view class="shop-info__name">{{ shopInfo.name }}</view>
          <view class="shop-info__table">
            <u-icon name="table" size="24" color="#fa436a" class="icon-margin"></u-icon>
            {{ tableInfo.name }}
          </view>
        </view>
      </view>
    </view>
    
    <!-- 购物车列表 -->
    <scroll-view class="cart-list" scroll-y>
      <!-- 有商品 -->
      <block v-if="cartStore.state.items.length > 0">
        <view
          class="cart-item"
          v-for="(item, index) in cartStore.state.items"
          :key="index"
          :class="{'cart-item-slide': item.sliding}"
          @touchstart="touchStart($event, index)"
          @touchmove="touchMove($event, index)"
          @touchend="touchEnd($event, index)"
        >
          <view class="cart-item-content">
            <u-checkbox
              v-model="item.checked"
              @change="checkItem(item.id, $event)"
              shape="circle"
              activeColor="#fa436a"
              class="item-checkbox"
            ></u-checkbox>
            <u-image class="item-image" :src="item.thumbnail || '/static/default-dish.png'" mode="aspectFill" radius="6"></u-image>
            <view class="item-info">
              <view class="item-name">{{ item.name }}</view>
              <view class="item-spec" v-if="item.specification">
                <u-tag size="mini" text="规格" type="info" plain shape="circle" class="spec-tag"></u-tag>
                {{ item.specification }}
              </view>
              <view class="item-price-row">
                <view class="item-price">
                  <text class="price-symbol">￥</text>
                  <text class="price-value">{{ formatMoney(item.price) }}</text>
                </view>
                <view class="item-quantity">
                  <u-number-box
                    v-model="item.quantity"
                    @change="updateItemQuantity(item.id, $event)"
                    :min="0"
                    :max="99"
                    bgColor="#f8f8f8"
                    color="#fa436a"
                    size="mini"
                  ></u-number-box>
                </view>
              </view>
            </view>
          </view>
          <!-- 滑动删除按钮 -->
          <view class="cart-item-delete" @click.stop="removeItem(item.id)">
            <u-icon name="trash" color="#fff" size="44"></u-icon>
          </view>
        </view>
        
        <!-- 底部操作 -->
        <view class="cart-footer">
          <view class="cart-tips">左滑商品可删除单项，如需清空购物车请点击下方按钮</view>
          <view class="cart-actions">
            <u-button
              type="error"
              size="medium"
              icon="trash"
              shape="circle"
              plain
              @click="confirmClearCart"
              text="清空购物车"
            ></u-button>
          </view>
        </view>
      </block>
      
      <!-- 空购物车 -->
      <view v-else class="empty-cart">
        <u-empty text="购物车空空如也，快去挑选美食吧" mode="cart" icon="shopping-cart"></u-empty>
        <view class="empty-action">
          <u-button
            type="primary"
            size="medium"
            shape="circle"
            icon="shopping-cart"
            text="去点餐"
            @click="goToMenu"
            :customStyle="{background: 'linear-gradient(90deg, #fa436a, #F56C6C)'}"
          ></u-button>
        </view>
      </view>
    </scroll-view>
    
    <!-- 结算栏 -->
    <view class="checkout-bar" v-if="cartStore.state.items.length > 0">
      <view class="checkout-all">
        <u-checkbox
          v-model="allChecked"
          @change="checkAll"
          shape="circle"
          activeColor="#fa436a"
          size="32"
        >全选</u-checkbox>
      </view>
      <view class="total-info">
        <view class="total-price">
          <text>合计：</text>
          <text class="price-symbol">￥</text>
          <text class="price-value">{{ formatMoney(totalSelectedPrice) }}</text>
        </view>
        <view class="total-quantity">已选{{ totalSelectedQuantity }}件</view>
      </view>
      <view class="checkout-btn">
        <u-button
          type="primary"
          size="default"
          shape="circle"
          text="去结算"
          @click="checkout"
          :customStyle="{background: 'linear-gradient(90deg, #fa436a, #F56C6C)'}"
        ></u-button>
      </view>
    </view>
    
    <!-- 清空购物车确认弹窗 -->
    <u-modal
      v-model="showClearCartModal"
      title="提示"
      content="确定要清空购物车吗？"
      showCancelButton
      confirmText="确定"
      cancelText="取消"
      confirmColor="#fa436a"
      @confirm="clearCart"
    ></u-modal>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app'
import cartStore from '@/common/store/cart.js';
import * as uniApi from '@/common/utils/uni-api.js';

// 状态管理
const showClearCartModal = ref(false);
const shopInfo = ref({
  name: '微餐饮门店',
  logo: '/static/logo.png'
});
const tableInfo = ref({
  name: '当前桌号：01'
});

// 触摸参数
const startX = ref(0);
const allChecked = ref(true);

// 初始化数据
const initData = () => {
  try {
    // 获取本地存储的餐桌信息
    const tableInfoStr = uni.getStorageSync('tableInfo');
    if (tableInfoStr) {
      const data = JSON.parse(tableInfoStr);
      tableInfo.value = data;
      shopInfo.value = data.shopInfo || {};
    }
    
    // 初始化商品选中状态
    initItemChecked();
  } catch (e) {
    console.error('获取餐桌信息失败', e);
  }
};

// 初始化商品选中状态
const initItemChecked = () => {
  cartStore.state.items.forEach(item => {
    if (item.checked === undefined) {
      item.checked = true;
    }
    if (item.sliding === undefined) {
      item.sliding = false;
    }
  });
  updateAllChecked();
};

// 更新全选状态
const updateAllChecked = () => {
  if (cartStore.state.items.length === 0) {
    allChecked.value = false;
    return;
  }
  
  allChecked.value = cartStore.state.items.every(item => item.checked);
};

// 格式化金额
const formatMoney = (money) => {
  return parseFloat(money).toFixed(2);
};

// 选中/取消选中单个商品
const checkItem = (id, checked) => {
  const item = cartStore.state.items.find(item => item.id === id);
  if (item) {
    item.checked = checked;
    updateAllChecked();
  }
};

// 全选/取消全选
const checkAll = (checked) => {
  cartStore.state.items.forEach(item => {
    item.checked = checked;
  });
};

// 计算选中商品的总价
const totalSelectedPrice = computed(() => {
  return cartStore.state.items.reduce((total, item) => {
    if (item.checked) {
      return total + item.price * item.quantity;
    }
    return total;
  }, 0);
});

// 计算选中商品的总数量
const totalSelectedQuantity = computed(() => {
  return cartStore.state.items.reduce((total, item) => {
    if (item.checked) {
      return total + item.quantity;
    }
    return total;
  }, 0);
});

// 更新商品数量
const updateItemQuantity = (id, quantity) => {
  if (quantity === 0) {
    // 数量为0，直接删除商品
    removeItem(id);
    return;
  }
  
  cartStore.updateItemQuantity(id, quantity);
};

// 展示清空购物车确认弹窗
const confirmClearCart = () => {
  showClearCartModal.value = true;
};

// 清空购物车
const clearCart = () => {
  cartStore.clearCart();
  uniApi.showToast('购物车已清空');
};

// 删除单个商品
const removeItem = (id) => {
  cartStore.removeFromCart(id);
  uniApi.showToast('商品已删除');
  updateAllChecked();
};

// 跳转到菜单页
const goToMenu = () => {
  uniApi.switchTab('/pages/menu/menu');
};

// 去结算
const checkout = () => {
  const selectedItems = cartStore.state.items.filter(item => item.checked);
  
  if (selectedItems.length === 0) {
    uniApi.showToast('请先选择商品');
    return;
  }
  
  uniApi.navigateTo('/pages/order/detail');
};

// 触摸开始
const touchStart = (e, index) => {
  // 记录起始触摸位置
  startX.value = e.touches[0].clientX;
  
  // 先复位其他项
  cartStore.state.items.forEach((item, idx) => {
    if (idx !== index) {
      item.sliding = false;
    }
  });
};

// 触摸移动
const touchMove = (e, index) => {
  const moveX = e.touches[0].clientX;
  const diffX = startX.value - moveX;
  
  const item = cartStore.state.items[index];
  
  // 向左滑动超过一定距离，显示删除按钮
  if (diffX > 60) {
    item.sliding = true;
  } else if (diffX < 0) {
    // 向右滑动，隐藏删除按钮
    item.sliding = false;
  }
};

// 触摸结束
const touchEnd = (e, index) => {
  const moveX = e.changedTouches[0].clientX;
  const diffX = startX.value - moveX;
  
  const item = cartStore.state.items[index];
  
  // 滑动距离小，复位
  if (diffX < 60) {
    item.sliding = false;
  }
};

// 页面显示时触发
onShow(() => {
  initData();
});

// 页面加载时触发
onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped>
.cart-container {
  background-color: #f8f8f8;
  min-height: 100vh;
  position: relative;
  padding-bottom: 120rpx;
}

.cart-header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 200rpx;
  background: linear-gradient(90deg, #fa436a, #F56C6C);
  border-radius: 0 0 40rpx 40rpx;
  z-index: 0;
}

.shop-info {
  position: relative;
  z-index: 1;
  padding: 30rpx;
}

.shop-info-inner {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.shop-logo {
  margin-right: 20rpx;
}

.shop-info-text {
  flex: 1;
}

.shop-info__name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 6rpx;
}

.shop-info__table {
  font-size: 24rpx;
  color: #666;
  display: flex;
  align-items: center;
}

.icon-margin {
  margin-right: 6rpx;
}

.cart-list {
  position: relative;
  z-index: 1;
  padding: 0 30rpx;
  margin-bottom: 30rpx;
  max-height: calc(100vh - 350rpx);
}

.cart-item {
  position: relative;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s;
  width: 100%;
  transform: translateX(0);
}

.cart-item-slide {
  transform: translateX(-140rpx);
}

.cart-item-content {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  width: 100%;
}

.item-checkbox {
  margin-right: 20rpx;
}

.item-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.item-info {
  flex: 1;
  overflow: hidden;
}

.item-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 10rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-spec {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 16rpx;
  display: flex;
  align-items: center;
}

.spec-tag {
  margin-right: 10rpx;
}

.item-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  font-size: 32rpx;
  color: #fa436a;
  font-weight: bold;
}

.price-symbol {
  font-size: 24rpx;
}

.price-value {
  font-size: 32rpx;
}

.cart-item-delete {
  position: absolute;
  top: 0;
  right: -140rpx;
  width: 140rpx;
  height: 100%;
  background-color: #fa436a;
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-cart {
  padding: 60rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-action {
  margin-top: 40rpx;
}

.cart-footer {
  padding: 20rpx 0 40rpx;
}

.cart-tips {
  text-align: center;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.cart-actions {
  display: flex;
  justify-content: center;
}

.checkout-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  height: 100rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.checkout-all {
  margin-right: 30rpx;
}

.total-info {
  flex: 1;
}

.total-price {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 4rpx;
}

.total-price .price-value {
  color: #fa436a;
  font-weight: bold;
}

.total-quantity {
  font-size: 24rpx;
  color: #999;
}

.checkout-btn {
  min-width: 200rpx;
}
</style>  